package top.xia17.plugins.fast.common.database.mybatis.other;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import lombok.Getter;

/**
 * mybatis-plus的雪花ID生成器
 *
 * @author xia17
 * @since 2022/2/16 15:04
 */
@Getter
public class SnowIdGenerator implements IdentifierGenerator {

    private Integer workerId;

    private Integer datacenterId;

    private Snowflake snowflake;

    public SnowIdGenerator() {
        this.resetSnowFlake(1, 1);
    }

    public SnowIdGenerator(Integer workerId, Integer datacenterId) {
        this.resetSnowFlake(workerId, datacenterId);
    }

    public void resetSnowFlake(Integer workerId, Integer datacenterId) {
        this.workerId = workerId;
        this.datacenterId = datacenterId;
        this.snowflake = new Snowflake(workerId, datacenterId);
    }


    @Override
    public Number nextId(Object entity) {
        return snowflake.nextId();
    }
}
